/**
 * 腾讯云COS连接测试脚本
 * 用于验证浏览器是否能访问COS API和文件
 */

// 测试配置
const testConfig = {
  // COS信息
  bucket: 'mybox-1257251314',
  region: 'ap-chengdu',
  cdnDomain: 'https://cos.roginx.ink',
  domain: 'https://mybox-1257251314.cos.ap-chengdu.myqcloud.com',
  testPrefix: 'www/educoder/file/',
  
  // 测试文件
  testFile: 'test.txt'
};

// 延迟函数
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

// 获取DOM元素
const logElement = document.getElementById('log');
const resultElement = document.getElementById('result');

// 添加日志
function addLog(message, type = 'info') {
  if (!logElement) return;
  
  const logItem = document.createElement('div');
  logItem.className = `log-item log-${type}`;
  logItem.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
  
  logElement.appendChild(logItem);
  logElement.scrollTop = logElement.scrollHeight;
}

// 设置结果
function setResult(success, message) {
  if (!resultElement) return;
  
  resultElement.className = success ? 'success' : 'failure';
  resultElement.textContent = message;
}

// 测试直接访问
async function testDirectAccess() {
  addLog('测试直接访问文件...');
  
  try {
    const url = `${testConfig.domain}/${testConfig.testPrefix}${testConfig.testFile}`;
    addLog(`请求URL: ${url}`);
    
    const response = await fetch(url);
    
    if (response.ok) {
      const text = await response.text();
      addLog(`文件访问成功! 内容长度: ${text.length} 字节`);
      return true;
    } else {
      addLog(`文件访问失败! 状态码: ${response.status}`, 'error');
      return false;
    }
  } catch (error) {
    addLog(`访问异常: ${error.message}`, 'error');
    return false;
  }
}

// 测试CDN访问
async function testCdnAccess() {
  addLog('测试通过CDN访问文件...');
  
  try {
    const url = `${testConfig.cdnDomain}/${testConfig.testPrefix}${testConfig.testFile}`;
    addLog(`请求URL: ${url}`);
    
    const response = await fetch(url);
    
    if (response.ok) {
      const text = await response.text();
      addLog(`CDN访问成功! 内容长度: ${text.length} 字节`);
      return true;
    } else {
      addLog(`CDN访问失败! 状态码: ${response.status}`, 'error');
      return false;
    }
  } catch (error) {
    addLog(`CDN访问异常: ${error.message}`, 'error');
    return false;
  }
}

// 测试CORS
async function testCors() {
  addLog('测试CORS设置...');
  
  try {
    const url = `${testConfig.domain}/${testConfig.testPrefix}`;
    addLog(`发送OPTIONS请求: ${url}`);
    
    const response = await fetch(url, {
      method: 'OPTIONS',
      headers: {
        'Origin': window.location.origin,
        'Access-Control-Request-Method': 'GET'
      }
    });
    
    addLog(`CORS响应状态: ${response.status}`);
    
    const allowOrigin = response.headers.get('Access-Control-Allow-Origin');
    const allowMethods = response.headers.get('Access-Control-Allow-Methods');
    
    addLog(`Access-Control-Allow-Origin: ${allowOrigin || '未设置'}`);
    addLog(`Access-Control-Allow-Methods: ${allowMethods || '未设置'}`);
    
    if (allowOrigin && allowMethods) {
      addLog('CORS配置正确!');
      return true;
    } else {
      addLog('CORS配置可能有问题', 'warning');
      return false;
    }
  } catch (error) {
    addLog(`CORS测试异常: ${error.message}`, 'error');
    return false;
  }
}

// 主测试函数
async function runTests() {
  addLog('开始COS连接测试...');
  addLog(`时间戳: ${Date.now()}`);
  
  let success = true;
  
  // 测试直接访问
  if (!await testDirectAccess()) {
    success = false;
  }
  
  await delay(1000);
  
  // 测试CDN访问
  if (!await testCdnAccess()) {
    success = false;
  }
  
  await delay(1000);
  
  // 测试CORS
  if (!await testCors()) {
    // CORS问题只是警告，不直接判定为失败
    addLog('CORS配置可能有问题，但不影响基本访问', 'warning');
  }
  
  // 设置最终结果
  if (success) {
    setResult(true, '✅ 测试通过! COS服务可正常访问。');
    addLog('所有测试通过!');
  } else {
    setResult(false, '❌ 测试失败! 请检查配置和网络。');
    addLog('部分测试未通过，请检查详细日志', 'error');
  }
}

// 如果页面已加载，执行测试
if (document.readyState === 'complete') {
  runTests();
} else {
  // 否则等待页面加载完成
  window.addEventListener('load', runTests);
} 